package job.component;

import java.util.List;

import job.entity.JobInfo;
import job.utils.MathSalary;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;
/*
 * 页面解析的核心业务逻辑
 * 
 * */
public class JobPageProcessor implements PageProcessor {
/*
 * 对页面进行解析
 * 
 * */
	@Override
	public void process(Page page) {
		//判断是列表还是详情
		Html html = page.getHtml();
		List<Selectable> nodes = html.css("div.e > a.el").nodes();
		String nextUrl = "";
		int i;
		if(nodes.size() > 0) {
			//解析详情页url和下一页url
			List<String> links = html.links().all();
			page.addTargetRequests(links);
			
			i = Integer.parseInt(html.css("span.td:nth-child(1)","text").get());
			nextUrl = "https://search.51job.com/list/180200,000000,0000,00,9,99,java,2,"+i+".html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare=";
			page.addTargetRequest(nextUrl);
		    //跳过pipeline
			page.getResultItems().setSkip(true);
		}else {
			//解析详情页
			parseJobInfo(page);
			
		}
	
	}
	
	private void parseJobInfo(Page page) {
		Html html = page.getHtml();
		
//		     公司名称
		String companyName = html.css(".catn","text").get();
//           公司联系方式
		String companyAddr = html.css("div.tBorderTop_box:nth-child(2) > div:nth-child(2) > p:nth-child(1)","text").get();
//           公司信息
		String companyInfo = html.css("div.tBorderTop_box:nth-child(3)","text").get();
//           职位名称
		String jobName = html.css(".cn > h1:nth-child(1)","text").get();
//           工作地点
		String jobAddr = "";
		String[] headers = html.css(".msg","title").get().split("//|");
		 if(headers.length > 0) {
			 jobAddr = headers[0];
		 }	 
//           职位信息
		String jobInfoStr = html.css(".tCompany_main > div:nth-child(1)","text").smartContent().get();
//           薪资范围
		String salaryStr = html.css(".cn > strong:nth-child(2)","text").get();
		Integer[] salary = MathSalary.getSalary(salaryStr);
		int salaryMin = salary[0];
		int salaryMax = salary[1];
//           招聘信息详情页
		String url = page.getUrl().get();
//           职位最近发布时间
		String time = "";
		for(String s:headers) {
			if(s.contains("发布")) {
				time = s.substring(0,s.lastIndexOf("发"));
				break;
			}
		}
		//封装为JobInfo对象
		JobInfo jobInfo = new JobInfo();
		jobInfo.setCompanyName(companyName);
		jobInfo.setCompanyAddr(companyAddr);
		jobInfo.setCompanyInfo(companyInfo);
		jobInfo.setJobName(jobName);
		jobInfo.setJobAddr(jobAddr);
		jobInfo.setJobInfo(jobInfoStr);
		jobInfo.setSalaryMin(salaryMin);
		jobInfo.setSalaryMax(salaryMax);
		jobInfo.setUrl(url);
		jobInfo.setTime(time);
	}

	@Override
	public Site getSite() {
		
		return Site.me();
	}

}
